package info.wangyuan.agent.utils;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MailUtil {

    private final JavaMailSender javaMailSender;

    public MailUtil(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送简单文本邮件
     */
    public void sendTextMail(String from, String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            javaMailSender.send(message);
            log.info("✅ [邮件发送成功] to={} subject={}", to, subject);
        } catch (Exception e) {
            log.error("❌ [邮件发送失败] to={} subject={}", to, subject, e);
        }
    }

    /**
     * 发送HTML格式邮件
     */
    public void sendHtmlMail(String from, String to, String subject, String htmlContent) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            javaMailSender.send(mimeMessage);
            log.info("✅ [HTML邮件发送成功] to={} subject={}", to, subject);
        } catch (Exception e) {
            log.error("❌ [HTML邮件发送失败] to={} subject={}", to, subject, e);
        }
    }
}
